﻿
///////////////////////////////////////////////////////////
//This code is taken from the Channel9 video tutorials.
//They are here for convenience - check the web link in the
//folder for each of these to see the original postings.
//
//These challenges are completed - the uncompleted ones are in
//a subfolder below this one, named OriginalCode
//////////////////////////////////////////////////////////////

using System;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Forms;
using WritingQueries.DictionaryService;

namespace WritingQueries
{
    static class Program
    {
        static void Main(string[] args)
        {
            var txt = new TextBox();
            var lst = new ListBox { Top = txt.Height + 10 };
            var frm = new Form { Controls = { txt, lst } };

            var textChanged = Observable.FromEventPattern<EventHandler, EventArgs>(h => txt.TextChanged += h, h => txt.TextChanged -= h);
                    
            var getSuggestions = Observable.FromAsyncPattern<string, DictionaryWord[]>(BeginMatch, EndMatch);

			var lookup = textChanged
							.Select(_ => txt.Text)
							.DistinctUntilChanged()
							.Throttle(TimeSpan.FromMilliseconds(200))
							.Do(text => Console.WriteLine("TextChanged: {0}", text))
							.Where(text => text.Length >= 3)
							.Do(text => Console.WriteLine("Lookup: {0}", text));

			var results = lookup
						  .Select(text => getSuggestions(text))
						  .Switch();

            using (results
                .ObserveOn(lst)
                .Subscribe(words =>
                {
                    lst.Items.Clear();
                    lst.Items.AddRange(words.Select(word => word.Word).Take(10).ToArray());
                }))
            {
                Application.Run(frm);
            }
        }

        static DictServiceSoapClient service = new DictServiceSoapClient("DictServiceSoap");

        static IAsyncResult BeginMatch(string prefix, AsyncCallback callback, object state)
        {
            return service.BeginMatchInDict("wn", prefix, "prefix", callback, state);
        }

        static DictionaryWord[] EndMatch(IAsyncResult result)
        {
            return service.EndMatchInDict(result);
        }
    }
}
